<template>
  <view class="msg-code-box">
    <!-- 获取验证码按钮 -->
    <view
      class="code-btn"
      :style="{ color: countDown > 0 ? '#F1B444' : '#F1B444' }"
      @click="getCode"
    >
      {{ countDown > 0 ? `${countDown}秒重新获取` : "获取验证码" }}
    </view>
  </view>
</template>

<script setup>
import { reactive, ref } from "vue";
// import { TFormItem, TInput, TImage } from 'tdesign-vue-mobile';
import { Message, Toast } from "tdesign-mobile-vue";
import loginApi from "@/api/loginApi"; // 替换为你的实际接口

// Props
const props = defineProps({
  phone: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    default: "login", // login / bindPhone 等场景
  },
});

// 响应式数据
const formState = reactive({
  msg: "",
});
const countDown = ref(0); // 倒计时
const codeIcon = ref("@/assets/login/code.png"); // 图标

// 倒计时逻辑
const startCountDown = () => {
  countDown.value = 60;
  const timer = setInterval(() => {
    countDown.value--;
    if (countDown.value <= 0) clearInterval(timer);
  }, 1000);
};

// 检查手机号是否被注册
const existPhone = async () => {
  if (props.type === "bingPhone") {
    const result = await commonApi.existPhone(props.phone);
    const isBind = result.data;
    if (isBind) {
      Toast({
        duration: 800,
        message: "手机号已被绑定",
      });
    }
    return isBind;
  }
};

const getCode = async () => {
  if (props.phone == "") {
    // Message.warning('请输入手机号码');
    Toast({
      duration: 800,
      message: "请输入手机号码",
    });
    return;
  }
  if (!/^1\d{10}$/.test(props.phone)) {
    // Message.warning('手机号码格式不正确');
    Toast({
      duration: 800,
      message: "手机号码格式不正确",
    });
    return;
  }
  if (countDown.value > 0) {
    return;
  }
  startCountDown();
  const isBind = await existPhone();
  if (!isBind) {
    const result = await loginApi.sendMsg(props.phone, "login"); // state 是状态 可以是login,forget,bindWx,bindIos。目前就先都传login
    if (result.code === 0) {
      Message.success("验证码发送成功");
    } else {
      Message.error(result.msg);
    }
  }
};
</script>

<style lang="scss" scoped>
.msg-code-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 30px;

  .form-item {
    flex: 1;
    border-bottom: rgba(0, 0, 0, 0.1) solid 1px;
    margin-top: 20px;
    padding-bottom: 10px;

    ::v-deep .t-input {
      font-size: 14px;
    }
  }

  .code-btn {
    font-size: 18px;
    font-weight: 550;
    color: #f1b444;
    cursor: pointer;
    margin-left: 10px;

    &:active {
      opacity: 0.8;
    }
  }
}
</style>
